package cn.edu.jlu.community.app.home;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.squareup.picasso.Picasso;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.edu.jlu.community.R;
import cn.edu.jlu.community.app.MainActivity;
import cn.edu.jlu.community.app.post.PostContentFragment;
import cn.edu.jlu.community.server.AppServer;


public class PostGalleryFragment extends Fragment
        implements AppServer.LoaderCallback {

//    @InjectView(R.id.recycler_view)
//    RecyclerView mRecyclerView;

    private static final String ARG_CATEGORY = "category";
    private static final String ARG_TITLE = "title";
    private static final String ARG_TARGET = "target";

    private int mCategory = AppServer.FORUM_CATEGORY;
    private String mTitle = "加载中";
    private Target mTarget;

    public interface Target {
        public void run();
    }

    public static PostGalleryFragment newInstance(int category, String title, Target target) {
        PostGalleryFragment fragment = new PostGalleryFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_CATEGORY, category);
        args.putString(ARG_TITLE, title);
        fragment.setArguments(args);
        fragment.setTarget(target);
        return fragment;
    }

    private void setTarget(Target target) {
        mTarget = target;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public PostGalleryFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mCategory = getArguments().getInt(ARG_CATEGORY);
            mTitle = getArguments().getString(ARG_TITLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_post_gallery_fragment, container, false);
        ButterKnife.inject(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        AppServer.loadDataWithImageByCategory(mCategory, this);

        TextView headText = ButterKnife.findById(getView(), R.id.head_title);
        headText.setText(mTitle);
    }

    @OnClick(R.id.header)
    public void onClick() {
        mTarget.run();
    }

    public void onRefresh() {
        AppServer.loadDataWithImageByCategory(mCategory, this);
    }

    @Override
    public void onFinish(Object data) {
        final MainActivity context = (MainActivity) getActivity();
        if (null != context) {
//            HomeFragment fragment = (HomeFragment) context.getCurrentSection().getTargetFragment();
            HomeFragment fragment = (HomeFragment) context.getHomeFragment();
            fragment.getSwipeRefreshLayout().setRefreshing(false);
        }

        List<AVObject> dataSet = (List<AVObject>) data;

        int[] ids = {R.id.card1, R.id.card2, R.id.card3};
        List<View> cards = new ArrayList<>();
        for (int id : ids) {
            cards.add(ButterKnife.findById(getView(), id));
        }

        for (int i = 0; i < dataSet.size() && i < cards.size(); i++) {
            View card = cards.get(i);
            final AVObject e = dataSet.get(i);

            card.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    Map<String, Object> map = new HashMap<>();
                    bundle.putString("title", e.get("title").toString());
                    bundle.putString("objId", e.getObjectId());
                    bundle.putString("author", ((AVUser) e.get("from")).getUsername());
                    bundle.putString("author_id", ((AVUser) e.get("from")).getObjectId());
                    bundle.putString("content", e.get("content").toString());
                    DateFormat formatter = SimpleDateFormat.getDateTimeInstance();
                    bundle.putString("time", formatter.format(e.getUpdatedAt()));

                    context.setFragmentChild(
                            PostContentFragment.newInstance(bundle), "查看主题");
                }
            });

            TextView title = ButterKnife.findById(card, R.id.title);
            title.setText(e.getString("title"));

            ImageView image = ButterKnife.findById(card, R.id.image);
            AVFile drawing = (AVFile) (e.get("drawing"));
            Picasso.with(getActivity()).load(drawing.getUrl())
                    .placeholder(R.drawable.placeholder).into(image);
        }
    }

    @Override
    public void onError(AVException e) {

    }
}
